package com.zyx.ip2region.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zyx
 * @since 2021/9/1 20:42
 */
public class AuxUtil {

    private static final Pattern INTEGER_REGEX = Pattern.compile("[0-9]*");
    private static final String ZERO = "0";

    /**
     * 重写Utils的该方法, 加入判断是否为整数逻辑
     * @param ip 需要解析的ip
     * @return 解析后的Region信息
     */
    public static boolean isIpAddress(String ip) {

        String[] p = ip.split("\\.");
        if (p.length != 4) {
            return false;
        }

        for (String pp : p) {
            if (pp.length() > 3) {
                return false;
            }
            if (!isPositiveInteger(pp)) {
                System.out.println(pp + "is not integer");
                return false;
            }
            int val = Integer.parseInt(pp);
            if (val > 255) {
                return false;
            }
        }

        return true;
    }

    public static boolean isPositiveInteger(String str) {
        Matcher isNum = INTEGER_REGEX.matcher(str);
        return isNum.matches();
    }

    public static String convert(String addr) {
        return ZERO.equals(addr) ? "" : addr;
    }

}
